#include "protocol_handler.hpp"
#include "../common/logger.hpp"

void MessageHandler::register_protocol(const std::string &message_type, std::shared_ptr<IProtocolHandler> protocol)
{
    Logger::info("Register protocol: {}", message_type);
    protocols_[message_type] = protocol;
}

void MessageHandler::handle_message(GameServer& game_server, const nlohmann::json &message, uint32_t session_id)
{
    try
    {
        std::string message_type = message["type"].get<std::string>();
        auto it = protocols_.find(message_type);
        if (it != protocols_.end())
        {
            if (it->second->validate(game_server, message, session_id))
            {
                it->second->process(game_server, message, session_id);
            }
            else
            {
                Logger::error("Invalid message format for type: {}", message_type);
            }
        }
        else
        {
            Logger::warn("Unknown message type: {}", message_type);
        }
    }
    catch (const std::exception &e)
    {
        Logger::error("Error processing message: {}", e.what());
    }
}